package com.gnrsoft.rpc.registry;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;

/**
 * 
 * <B>中文类名：客户端发现服务类</B><BR>
 * <B>概要说明：客户端去zookeeper中找服务端service，实现负载均衡</B><BR>
 * 
 * @author likun
 * @since 2017年7月19日
 */
public class ServiceDiscovery {

	private CountDownLatch countDownLatch = new CountDownLatch(1);
	private volatile List<String> dataList = new ArrayList<String>();

	private String registryAddress;

	public ServiceDiscovery() {
	}

	public ServiceDiscovery(String registryAddress) {
		this.registryAddress = registryAddress;

		ZooKeeper zooKeeper = connectServer();

		if (null != zooKeeper) {
			watchNode(zooKeeper);
		}

	}

	private void watchNode(ZooKeeper zooKeeper) {

		try {
			// 监听 /gnrRPC 所有子节点变化
			List<String> nodeList = zooKeeper.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {

				@Override
				public void process(WatchedEvent event) {

					if (event.getType() == Event.EventType.NodeChildrenChanged) {
						watchNode(zooKeeper);
					}

				}
			});
			List<String> dataList = new ArrayList<String>();

			for (String node : nodeList) {
				byte[] data = zooKeeper.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null);
				dataList.add(new String(data));
			}

			System.out.println(this.getClass().getName() + " node data = " + dataList);

			this.dataList = dataList;

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private ZooKeeper connectServer() {

		ZooKeeper zk = null;
		try {
			zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {

				@Override
				public void process(WatchedEvent event) {

					KeeperState ks = event.getState();
					EventType et = event.getType();
					if (ks.SyncConnected == ks) {
						if (EventType.None == et) {
							System.out.println("zookeeper connection scucess");
							countDownLatch.countDown();
						}
					}
				}
			});
			countDownLatch.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return zk;

	}

	/**
	 * 发现新节点
	 * 
	 * @return
	 */
	public String discover() {
		String data = null;
		int size = dataList.size();
		if (size > 0) {
			if (size == 1) {
				data = dataList.get(0);
				System.out.println(this.getClass().getName() + " using only data " + data);
			} else {
				data = dataList.get(ThreadLocalRandom.current().nextInt(size));
				System.out.println(this.getClass().getName() + " using random data " + data);
			}
		}
		return data;
	}

}
